package com.solocredit.finance.ui.user.act

import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.solocredit.finance.BuildConfig
import com.solocredit.finance.R
import com.solocredit.finance.databinding.ActMullaUserSettingBinding
import com.solocredit.finance.http.ApiService
import com.solocredit.finance.http.ApiService.addCommonParams
import com.solocredit.finance.http.ApiService.addRandomParams
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.http.IHttpCallback
import com.solocredit.finance.mvp.ProAct
import com.solocredit.finance.utils.dialog.UserDataClearDialog
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.FlexiMolaUpdateHelper
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.SharedHelper
import org.json.JSONArray
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/16 16:16
 * @Annotation：设置
 */
class MullaUserSettingAct: ProAct() {
    lateinit var binding: ActMullaUserSettingBinding

    private var updateHelper: FlexiMolaUpdateHelper? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
        } else {
        }
    }

    override fun getMullaRootView(): View {
        binding = ActMullaUserSettingBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        setMullaTitleBarVisibility(View.VISIBLE)
        setMullaTextTitle(getString(R.string.user_help_setting))
        setMullaBackBtnRes(R.mipmap.mulla_back_black)
        setMullaRightBtnRes(R.mipmap.mulla_kefu_icon)
    }

    override fun initMullaListener() {
        //客服
        rootViewBinding.ivFun.setOnClickListener {
            showMullaKefuDialog("Setting Page")
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,"Setting Page")
        }

        // TODO: 测试点击版本号 增加积分
        binding.textVersion.setOnClickListener {
//            MullaUserPointsHelper.saveMullsUserPointsAction("testAddPoints","Test Add Points","100000")
        }

        //检查版本更新
        binding.checkAppUpdate.setOnClickListener {
            //是否有新版本
            val isUpdate = MullaCustomConfigsHelper.isFlexiMolaUpdate()
            if (!isUpdate){
                showMullaToast(getString(R.string.dialog_update_no_version))
                return@setOnClickListener
            }
            if (updateHelper == null){
                updateHelper = FlexiMolaUpdateHelper(this, false, updateLauncher)
            }
            updateHelper?.onFlexiMolaCheckVersionUpdate { }
        }

        //清空用户数据
        binding.btnClearData.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_USER_DATA_CLEAR)
            //存在未结清的账单
            if (isMullaCheckUncleared()){
                showMullaErrorTipsDialog(getString(R.string.user_data_clear_error),"Setting Page")
                return@setOnClickListener
            }
            showMullaClearDataDialog()
        }

        //退出登录
        binding.btnLoginOut.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_USER_LOGINOUT,"")
            //退出登录，需要移除用户保存的信息
            SharedHelper.onMullaLoginOut()
            Handler(Looper.getMainLooper()).postDelayed({
                onIntent(MullaUserLoginAct::class.java)
            },300)
        }
    }

    override fun initMullaData() {
        //获取版本名称
        binding.textVersion.text = String.format(getString(R.string.user_version),BuildConfig.VERSION_NAME)

        binding.btnClearData.visibility = View.GONE
        // TODO: 用最新的接口逻辑判断是否显示删除数据按钮
        loadMullaUserClearDataAction(true)
//        //是否显示清空用户数据
//        val isShowClearData = MullaCustomConfigsHelper.isMullaClearUserData()
//        if (isShowClearData){
//            binding.btnClearData.visibility = View.VISIBLE
//        } else {
//            binding.btnClearData.visibility = View.GONE
//        }

        //是否有新版本
        val isUpdate = MullaCustomConfigsHelper.isFlexiMolaUpdate()
        if (isUpdate){
            binding.viewUserNewVersion.visibility = View.VISIBLE
        } else {
            binding.viewUserNewVersion.visibility = View.GONE
        }

        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(licenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 是否存在未结清的账单
     */
    private fun isMullaCheckUncleared(): Boolean{
        val pData = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_PRODCTS)
        if (pData.isNotEmpty()){
            val objArray = JSONArray(pData)
            for (i in 0..<objArray.length()){
                val item = objArray.optJSONObject(i)
                val status = item.optString("status")
                //存在 审核中、放款中 || 待还款
                if (status == "PENDING" || status == "REPAYMENT"){
                    return true
                }
            }
        }
        return false
    }

    /**
     * 清空用户数据dialog
     */
    private fun showMullaClearDataDialog(){
        val clearDialog = UserDataClearDialog(this,object : UserDataClearDialog.IDialogCallback{
            override fun onMullaConfirmClick() {
                loadMullaUserClearDataAction(false)
            }
        })
        clearDialog.setCancelable(true)
        clearDialog.setCanceledOnTouchOutside(true)
        clearDialog.show()
    }

    /**
     * 清除用户数据 或 获取是否显示删除数据按钮
     */
    private fun loadMullaUserClearDataAction(isShowButton: Boolean){
        showMullaLoading()
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.MULLA_API_USER_DATA_CLEAR_PATH)
        val params = JSONObject().addCommonParams().addRandomParams().apply {
        }
        if (isShowButton){
            params.put("type","GET")
        } else {
            params.put("type","DROP")
        }
        HttpHelper.postMullaAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hideMullaLoading()
                if (isShowButton){
                    val obj = data.optJSONObject("obj")
                    if (obj != null && obj.has("showDropButton") && obj.optString("showDropButton") == "YES"){
                        binding.btnClearData.visibility = View.VISIBLE
                    } else {
                        binding.btnClearData.visibility = View.GONE
                    }
                } else {
                    //退出登录，需要移除用户保存的信息
                    SharedHelper.onMullaLoginOut()
                    onIntent(MullaUserLoginAct::class.java)
                }
            }
            override fun onRequestError(error: JSONObject) {
                showMullaToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                hideMullaLoading()
            }
        })
    }

    override fun onResume() {
        super.onResume()
        try {
            updateHelper?.onResumeFlexiMolaInProgress()
        } catch (e: Exception) {
            //
        }
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_USER_SETTING_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_USER_SETTING_END)
    }
}